package main

import (
	"github.com/sentiger/go-gateway/src"
	_ "github.com/sentiger/go-gateway/src/filters"
	"net/http"
	"net/http/httputil"
	"net/url"
)

func main() {
	routes := src.InitConfig()
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		if r := routes.Match(request); r != nil {
			webExchange := src.BuildServerWebExchange(request)
			rspFilters := r.Filter(webExchange)
			remote, _ := url.Parse(r.Url)
			p := httputil.NewSingleHostReverseProxy(remote)

			// 这里是修改响应，所以接下来可以做响应过滤器
			p.ModifyResponse = func(response *http.Response) error {
				rspFilters.Filter(response)
				return nil
			}
			p.ServeHTTP(writer, request)
		} else {
			writer.WriteHeader(http.StatusNotFound)
		}
	})
	http.ListenAndServe(":8089", nil)
}
